<script>
import ut from '@/assets/utils'
import dayjs from 'dayjs'
export default {
  name: 'UserAvatar',
  props: {
    avatar: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      imageURL: '',
      token: ut.storage.get('TK'),
      fileName: ''
    }
  },
  methods: {
    // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUpload(file) {
      // 限制文件类型
      const fileType = file.type
      if (fileType !== 'image/jpeg' && fileType !== 'image/png') {
        this.$message.error('只能上传 JPG 或 PNG 图片')
        return false
      }

      //限制文件大小
      const size = file.size
      if (size > 500 * 1024) {
        this.$message.warning('上传的图片不能超过500KB')
        return false
      }

      return true
    },

    updateUserImg() {
      // 更改图片名称
      const name = this.avatar
      this.fileName = this.formatterAvatar(name)
    },
    // 自定义请求
    async request({ file }) {      
      try {
        let { code, msg, url } = await this.$API.uploadUserImage(file)
        if (+code === 200) {
          this.imageURL = url
          this.$message.success('恭喜你，上传成功')
          return
        }
        this.$message.error(msg)
      } catch (_) {}
    },

    // 格式化头像文件名
    formatterAvatar(oldName) {
      if (typeof oldName !== 'string') return

      const regex = /(.+)(?:\.png|\.jpg)/
      const matches = oldName.match(regex)

      let fileNum = 0
      if (matches && matches.length >= 2) {
        // 获取文件后三位数
        fileNum = matches[1].slice(-3)
      }

      const newName = this.formatterFileTime() + this.padZero(+fileNum)
      return newName
    },
    // 格式化当前时间
    formatterFileTime() {
      let time = new Date(),
        dateFormat = '',
        dateStr = ''

      dateFormat = dayjs(time).format('YYYY/MM/DD')
      dateStr = dayjs(time).format('YYYYMMDDHHmmss')

      return `${dateFormat}/blob_${dateStr}A`
    },
    // 补零
    padZero(num) {
      if (num >= 100) {
        return String(num + 1)
      } else if (num >= 10) {
        return '0' + (num + 1)
      } else {
        return '00' + (num + 1)
      }
    }
  },
  created() {
    console.log(this.avatar)
  }
}
</script>

<template>
  <!-- <div class="userAvatar-box">
    <el-upload class="avatar-uploader " :action="fileHttp" :show-file-list="false" :before-upload="beforeUpload" :on-success="uploadSuccess" :on-error="uploadError" :headers="{Authorization:token}" :name="fileName" :http-request="request">
      <div class="avatar-box" @click="abc">
        <div class="mask"></div>
        <img v-if="avatar" :src="mixinPrefixAdd(avatar)">
      </div>
    </el-upload>
  </div> -->

  <div class="userAvatar-box">
    <el-upload class="avatar-uploader " action=""  :show-file-list="false" accept="image/*" :name="fileName" :before-upload="beforeUpload" :headers="{Authorization:token}" :http-request="request">
      <div class="avatar-box" @click="updateUserImg">
        <div class="mask"></div>
        <img v-if="avatar" :src="mixinPrefixAdd(avatar)">
      </div>
    </el-upload>
  </div>
</template>

<style lang="less" scoped>
.avatar-box {
  position: relative;
  width: 120px;
  height: 120px;
  .mask {
    position: absolute;
    background: rgba(0, 0, 0, 0.3);
    display: none;
  }
  .mask::before {
    content: '+';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 20px;
    color: #f5f5f5;
  }

  img,
  .mask {
    width: 100%;
    height: 100%;
    border-radius: 50% !important;
  }

  &:hover .mask {
    display: block;
  }
}
</style>